
package projectx.transaction;

import java.sql.Connection;
import java.sql.SQLException;

import projectx.core.base.ProjectXSystemException;
import projectx.core.base.ProjectXUserException;
import projectx.db.DbUtil;
import projectx.db.ProjectXConnectionManager;
import projectx.db.ProjectXSQLException;

public abstract class DatabaseTransaction extends Transaction {

    //--------------------------------------------------------------------------
    //   S T A T I C   M E M B E R S
    //
    //--------------------------------------------------------------------------
    private static final long   INTERVAL_MSEC = 30 * 1000; // 30 sec


    //--------------------------------------------------------------------------
    //   M E M B E R S
    //
    //--------------------------------------------------------------------------
    protected Connection    _conn;


    //--------------------------------------------------------------------------
    //   C O N S T R U C T O R S
    //
    //--------------------------------------------------------------------------

    protected DatabaseTransaction(){

        super( null, INTERVAL_MSEC );
    }

    protected DatabaseTransaction( String funcId ){

        super( DbUtil.chopId( funcId ), INTERVAL_MSEC );
    }


    //--------------------------------------------------------------------------
    //   M E T H O D S
    //
    //--------------------------------------------------------------------------
  
    public String getTrxType(){ return "db"; }

    public void initialize() throws ProjectXSystemException {

        _log.debug( "DB conn initialize" );
        _conn        = ProjectXConnectionManager.getConnection();
        _initialized = true;
    }

    public abstract Object execute() throws ProjectXUserException, ProjectXSystemException;

    public void commit() throws ProjectXSystemException {

        try {

            _log.debug( "DB commit" );
            _conn.commit();
        }
        catch ( SQLException e ){
            throw new ProjectXSQLException( e );
        }
    }

    public void rollback(){

        if ( _conn == null )    return;

        try {
            _log.debug( "DB rollback" );
            _conn.rollback();
        }
        catch ( SQLException e ){
            _log.error( new ProjectXSQLException( e ), e );
        }
    }

    public void release(){

        _initialized = false;

        if ( _conn == null )    return;

        try {
            _log.debug( "DB conn close" );
            _conn.close();
        }
        catch ( SQLException e ){
            _log.error( new ProjectXSQLException( e ), e );
        }
    }
}
